//
//  SZCViewController.m
//  地图
//
//  Created by dllo on 16/5/19.
//  Copyright © 2016年 sunzhichao. All rights reserved.
//

#import "SZCViewController.h"
#import "MAMutablePolyline.h"
#import "MAMutablePolylineView.h"
#import "StatusView.h"
#import "TipView.h"
#import "Record.h"
#import "FileHelper.h"
#import "RecordViewController.h"


@interface SZCViewController ()

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) MAMutablePolyline *mutablePolyline;
@property (nonatomic, strong) MAMutablePolylineView *mutableView;
@property (nonatomic, strong) StatusView *statusView;
@property (nonatomic, strong) TipView *tipView;
@property (nonatomic, strong) Record *currentRecord;

@property (nonatomic, strong) UIButton *locationBtn;
@property (nonatomic, strong) UIImage *imageLocated;
@property (nonatomic, strong) UIImage *imageNotLocate;

@property (nonatomic, assign) BOOL isRecording;

@property (nonatomic, strong) NSMutableArray *locationsArray;



@end

@implementation SZCViewController

#pragma mark - MapView Delegate 地图视图委托
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (!updatingLocation)
    {
        return;
    }
    
    if (self.isRecording)
    {
        if (userLocation.location.horizontalAccuracy < 80 && userLocation.location.horizontalAccuracy > 0)
        {
            [self.locationsArray addObject:userLocation.location];
            
            NSLog(@"date: %@,now :%@",userLocation.location.timestamp,[NSDate date]);
            [self.tipView showTip:[NSString stringWithFormat:@"has got %ld locations",self.locationsArray.count]];
            
            [self.currentRecord addLocation:userLocation.location];
            
            [self.mutablePolyline appendPoint: MAMapPointForCoordinate(userLocation.location.coordinate)];
            
            [self.mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
            
            [self.mutableView referenceDidChange];
        }
    }
    
    [self.statusView showStatusWith:userLocation.location];
}

/*!
 @brief 当userTrackingMode改变时，调用此接口
 @param mapView 地图View
 @param mode 改变后的mode
 @param animated 动画
 */
- (void)mapView:(MAMapView *)mapView  didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated
{
    if (mode == MAUserTrackingModeNone)
    {
        [self.locationBtn setImage:self.imageNotLocate forState:UIControlStateNormal];
    }
    else
    {
        [self.locationBtn setImage:self.imageLocated forState:UIControlStateNormal];
        [self.mapView setZoomLevel:16 animated:YES];
    }
}

/*!
 @brief 根据overlay生成对应的View
 @param mapView 地图View
 @param overlay 指定的overlay
 @return 生成的覆盖物View
 */
- (MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAMutablePolyline class]])
    {
        MAMutablePolylineView *view = [[MAMutablePolylineView alloc] initWithMutablePolyline:overlay];
        view.lineWidth = 8.0;
        view.strokeColor = [UIColor redColor];
        _mutableView = view;
        return view;
    }
    return nil;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setTitle:@"我的路线"];
    
    [self initNavigatinBar];
    
    [self initMapView];
    
    [self initOverlay];
    
    [self statusView];
    
    [self initTipView];
    
    [self initLocationButton];
    
    [self initStatusView];
    
}

#pragma mark - 地图视图
- (void)initMapView {
    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    
    /* 设置mapview位置配置 */
    /** 是否显示用户位置*/
    self.mapView.showsUserLocation = true;
    /** 设定定位的最小更新距离。默认为kCLDistanceFilterNone，会提示任何移动*/
    self.mapView.distanceFilter = 10;
    /** 设定定位精度。默认为kCLLocationAccuracyBest*/
    self.mapView.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    /** 指定定位是否会被系统自动暂停。默认为YES。只在iOS 6.0之后起作用。*/
    self.mapView.pausesLocationUpdatesAutomatically = NO;
    
    self.mapView.delegate = self;
    
    [self.view addSubview:self.mapView];
}

#pragma mark - 覆盖层
- (void)initOverlay {
    self.mutablePolyline = [[MAMutablePolyline alloc] initWithPoints:@[]];
}

#pragma mark - 状态视图
- (void)initStatusView {
    self.statusView = [[StatusView alloc] initWithFrame:CGRectMake(5, 35, 150, 150)];
    
    [self.view addSubview:self.statusView];
}

#pragma mark - 提示视图
/** 提示视图*/
- (void)initTipView {
    self.locationsArray = [[NSMutableArray alloc] init];
    
    self.tipView = [[TipView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height*0.95, self.view.bounds.size.width, self.view.bounds.size.height*0.05)];
    
    [self.view addSubview:self.tipView];
}

#pragma mark - 按钮位置
- (void)initLocationButton
{
    self.imageLocated = [UIImage imageNamed:@"adjust_32px_1181638_easyicon.net"];
    self.imageNotLocate = [UIImage imageNamed:@"navigation_36px_1130721_easyicon.net"];
    
    self.locationBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, CGRectGetHeight(self.view.bounds)*0.8, 50, 50)];
    self.locationBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    self.locationBtn.backgroundColor = [UIColor clearColor];
    self.locationBtn.layer.cornerRadius = 5;
    [self.locationBtn addTarget:self action:@selector(actionLocation) forControlEvents:UIControlEventTouchUpInside];
    [self.locationBtn setImage:self.imageNotLocate forState:UIControlStateNormal];
    
    [self.view addSubview:self.locationBtn];
}

#pragma mark - Utility 实用程序

- (void)saveRoute
{
    if (self.currentRecord == nil)
    {
        return;
    }
    
    NSString *name = self.currentRecord.title;
    NSString *path = [FileHelper filePathWithName:name];
    
    [NSKeyedArchiver archiveRootObject:self.currentRecord toFile:path];
    
    self.currentRecord = nil;
}


#pragma mark - NavigationBar
- (void)initNavigatinBar {
    // 边缘长布局
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    /** 抽屉*/
    NSArray *leftButtonItems = @[[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"aligh_left_27.291428571429px_1189116_easyicon.net"] style:UIBarButtonItemStyleDone target:self action:@selector(BackToTheDrawer)],[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"play_arrow_32px_1182133_easyicon.net"] style:UIBarButtonItemStyleDone target:self action:@selector(actionRecordAndStop)]];
    
    self.navigationItem.leftBarButtonItems = leftButtonItems;
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"aligh_left_27.291428571429px_1189116_easyicon.net"] style:UIBarButtonItemStyleDone target:self action:@selector(BackToTheDrawer)];
    /** 开始运动*/
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"play_arrow_32px_1182133_easyicon.net"] style:UIBarButtonItemStyleDone target:self action:@selector(actionRecordAndStop)];
    
    /** 截取*/
    UIBarButtonItem *clearButton = [[UIBarButtonItem alloc] initWithTitle:@"截取" style:UIBarButtonItemStylePlain target:self action:@selector(actionClear)];
    
    /** 记录页*/
    UIBarButtonItem *listButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"More_Three_Dots_32px_1180706_easyicon.net"] style:UIBarButtonItemStylePlain target:self action:@selector(actionShowList)];
    
    
    NSArray *array = [[NSArray alloc] initWithObjects:listButton, clearButton, nil];
    
    self.navigationItem.rightBarButtonItems = array;
    
    self.isRecording = NO;
}

#pragma mark - 精确位置
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self.mapView addOverlay:self.mutablePolyline];
    
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
}

#pragma mark - 处理动作

#pragma mark - 操作记录和停止
- (void)actionRecordAndStop
{
    self.isRecording = !self.isRecording;
    
    if (self.isRecording)
    {
        [self.tipView showTip:@"开始记录"];
        self.navigationItem.leftBarButtonItem.image = [UIImage imageNamed:@"stop_32px_1171699_easyicon.net"];
        
        if (self.currentRecord == nil)
        {
            self.currentRecord = [[Record alloc] init];
        }
    }
    else
    {
        self.navigationItem.leftBarButtonItem.image = [UIImage imageNamed:@"aligh_left_27.291428571429px_1189116_easyicon.net"];
        [self.tipView showTip:@"已经停止记录"];
    }
}

#pragma mark - 截取
- (void)actionClear
{
    self.isRecording = NO;
    [self.locationsArray removeAllObjects];
    self.navigationItem.leftBarButtonItem.image = [UIImage imageNamed:@"aligh_left_27.291428571429px_1189116_easyicon.net"];
    [self.tipView showTip:@"已经停止记录"];
    [self saveRoute];
    
    [self.mutablePolyline removeAllPoints];
    
    [self.mutableView referenceDidChange];
}


/** 操作位置*/
- (void)actionLocation
{
    if (self.mapView.userTrackingMode == MAUserTrackingModeFollow)
    {
        [self.mapView setUserTrackingMode:MAUserTrackingModeNone];
    }
    else
    {
        [self.mapView setUserTrackingMode:MAUserTrackingModeFollow];
    }
}

#pragma mark - 行动截取列表
- (void)actionShowList
{
    UIViewController *recordController = [[RecordViewController alloc] initWithNibName:nil bundle:nil];
    recordController.title = @"Records";
    
    [self.navigationController pushViewController:recordController animated:YES];
}

#pragma mark - 抽屉
- (void)BackToTheDrawer
{
    [self.locker presentLeftMenuViewController];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
